import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Paper,
  TextField,
  InputAdornment,
  Button,
  IconButton,
  Grid,
  Card,
  CardContent,
  Chip,
  Divider,
  useTheme,
  Pagination,
  CircularProgress,
  Skeleton,
  FormControl,
  InputLabel,
  MenuItem,
  Select,
  SelectChangeEvent,
  Stack,
  Alert,
  Tooltip,
  Tabs,
  Tab,
  Menu,
  ListItemIcon,
  ListItemText,
  List,
  ListItem,
  ListSubheader,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextareaAutosize,
  FormHelperText,
  Snackbar,
  FormControlLabel,
  Switch,
} from '@mui/material';
import {
  ArrowBack as ArrowBackIcon,
  Search as SearchIcon,
  FilterList as FilterIcon,
  Clear as ClearIcon,
  ContentCopy as CopyIcon,
  MoreVert as MoreVertIcon,
  Visibility as VisibilityIcon,
  Tune as TuneIcon,
  LibraryBooks as SummaryIcon,
  Chat as DialogueIcon,
  Download as DownloadIcon,
  Edit as EditIcon,
  Refresh as RefreshIcon,
} from '@mui/icons-material';
import { useNavigate } from 'react-router-dom';
import { data as dataApi, chat } from '../services/api';
import { useUser } from '../contexts/UserContext';

// 摘要数据接口
interface Summary {
  id: number;
  fname?: string;
  dialogue: string;
  summary: string;
  keywords: string;
  coreference_id?: string;
  coreference_text?: string;
  upload_id: number;
  created_at: string;
  uploader?: {
    id: number;
    username: string;
  };
}

// 页面响应接口
interface SearchResponse {
  summaries: Summary[];
  total: number;
  page: number;
  per_page: number;
}

// 查询参数接口
interface SearchParams {
  query: string;
  page: number;
  per_page: number;
  search_type: 'summary' | 'dialogue' | 'keywords' | 'all';
  chat_only?: boolean;
}

const SummarySearch: React.FC = () => {
  const theme = useTheme();
  const navigate = useNavigate();
  const { currentUser } = useUser();
  
  // 搜索状态
  const [searchParams, setSearchParams] = useState<SearchParams>({
    query: '',
    page: 1,
    per_page: 10,
    search_type: 'all',
    chat_only: false,
  });
  const [searchValue, setSearchValue] = useState(''); // 用于控制输入框
  const [searchResults, setSearchResults] = useState<SearchResponse | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  
  // 详情展示状态
  const [selectedSummary, setSelectedSummary] = useState<Summary | null>(null);
  const [detailView, setDetailView] = useState<'summary' | 'dialogue'>('summary');
  const [detailDialogOpen, setDetailDialogOpen] = useState(false);  // 添加详情对话框状态
  
  // 筛选菜单状态
  const [filterAnchorEl, setFilterAnchorEl] = useState<null | HTMLElement>(null);
  const filterOpen = Boolean(filterAnchorEl);
  
  // 更多操作菜单状态
  const [moreAnchorEl, setMoreAnchorEl] = useState<null | HTMLElement>(null);
  const [activeSummaryId, setActiveSummaryId] = useState<number | null>(null);
  
  // 修改摘要的状态
  const [editDialogOpen, setEditDialogOpen] = useState(false);
  const [editedSummary, setEditedSummary] = useState('');
  const [selectedModel, setSelectedModel] = useState('model_1');
  const [regenerating, setRegenerating] = useState(false);
  
  // 添加消息提示状态
  const [successMessage, setSuccessMessage] = useState('');
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  
  // 首次加载时从 URL 读取参数
  useEffect(() => {
    // 从 URL 获取查询参数
    const searchParams = new URLSearchParams(window.location.search);
    const query = searchParams.get('q') || '';
    const search_type = searchParams.get('type') || 'all';
    const chat_only = searchParams.get('chat_only') === 'true';
    
    // 设置搜索参数和值
    setSearchValue(query);
    setSearchParams(prev => ({
      ...prev,
      query,
      search_type: search_type as 'summary' | 'dialogue' | 'keywords' | 'all',
      chat_only
    }));
    
    // 清除可能存在的错误状态
    setError('');
    
    // 不在这里直接调用 handleSearch，让依赖触发的 useEffect 去处理
  }, []);
  
  // 搜索参数变化时执行搜索，但只在必要时触发
  useEffect(() => {
    // 清除可能存在的错误状态
    setError('');
    
    // 避免空依赖数组的初始化重复触发
    const controller = new AbortController();
    
    // 延迟执行搜索，减少快速连续变更导致的请求
    const timeoutId = setTimeout(() => {
      handleSearch(controller.signal);
    }, 10);
    
    return () => {
      clearTimeout(timeoutId);
      controller.abort(); // 组件卸载或依赖变化时取消请求
    };
  }, [searchParams.query, searchParams.page, searchParams.per_page, searchParams.search_type]);
  
  const handleSearch = async (signal?: AbortSignal) => {
    try {
      setLoading(true);
      // 请求开始时不设置错误为空，避免闪烁
      
      const response = await dataApi.searchSummaries({
        query: searchParams.query.trim(),
        page: searchParams.page,
        per_page: searchParams.per_page,
        search_type: searchParams.search_type,
        chat_only: searchParams.chat_only
      }, signal);
      
      if (signal?.aborted) {
        // 如果请求已被取消，不更新状态
        return;
      }
      
      setSearchResults(response.data);
      // 请求成功后清除错误状态
      setError('');
      
      // 更新 URL 查询参数，但不修改 searchParams 避免循环
      const searchUrl = new URL(window.location.href);
      searchUrl.searchParams.set('q', searchParams.query);
      searchUrl.searchParams.set('type', searchParams.search_type);
      if (searchParams.chat_only) {
        searchUrl.searchParams.set('chat_only', 'true');
      } else {
        searchUrl.searchParams.delete('chat_only');
      }
      window.history.pushState({}, '', searchUrl);
    } catch (error: any) {
      // 忽略取消请求的错误
      if (error.name !== 'AbortError' && !signal?.aborted) {
        console.error('搜索失败:', error);
        setError(error.response?.data?.error || '搜索失败，请稍后重试');
      }
    } finally {
      // 如果请求已被取消，不更新loading状态
      if (!signal?.aborted) {
        setLoading(false);
      }
    }
  };
  
  const handleSearchSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    // 使用输入框的值更新搜索参数，触发 useEffect
    setSearchParams(prev => ({ 
      ...prev, 
      query: searchValue, 
      page: 1 
    }));
  };
  
  const handlePageChange = (event: React.ChangeEvent<unknown>, value: number) => {
    setSearchParams(prev => ({ ...prev, page: value }));
  };
  
  const handleSearchTypeChange = (event: SelectChangeEvent) => {
    setSearchParams(prev => ({
      ...prev,
      search_type: event.target.value as 'summary' | 'dialogue' | 'keywords' | 'all',
      page: 1, // 重置页码
    }));
  };
  
  const handleFilterClick = (event: React.MouseEvent<HTMLElement>) => {
    setFilterAnchorEl(event.currentTarget);
  };
  
  const handleFilterClose = () => {
    setFilterAnchorEl(null);
  };
  
  const handleMoreClick = (event: React.MouseEvent<HTMLElement>, summaryId: number) => {
    setMoreAnchorEl(event.currentTarget);
    setActiveSummaryId(summaryId);
  };
  
  const handleMoreClose = () => {
    setMoreAnchorEl(null);
    setActiveSummaryId(null);
  };
  
  const handleClearSearch = () => {
    setSearchValue('');
    // 更新搜索参数，触发新搜索
    setSearchParams({
      query: '',
      page: 1,
      per_page: 10,
      search_type: 'all',
      chat_only: false,
    });
    
    // 清除URL查询参数
    const searchUrl = new URL(window.location.href);
    searchUrl.searchParams.delete('q');
    searchUrl.searchParams.delete('type');
    window.history.pushState({}, '', searchUrl);
    
    // 清除错误状态
    setError('');
  };
  
  const handleDetailViewChange = (event: React.SyntheticEvent, newValue: 'summary' | 'dialogue') => {
    setDetailView(newValue);
  };
  
  const handleViewDetail = (summary: Summary) => {
    setSelectedSummary(summary);
    setMoreAnchorEl(null);
    setDetailDialogOpen(true);  // 打开详情对话框
  };
  
  const handleCopySummary = (text: string) => {
    navigator.clipboard.writeText(text)
      .then(() => {
        alert('已复制到剪贴板');
      })
      .catch(err => {
        console.error('复制失败:', err);
      });
    handleMoreClose();
  };
  
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };
  
  // 高亮搜索词
  const highlightText = (text: string, query: string) => {
    if (!query.trim() || !text) return text;
    
    try {
      const parts = text.split(new RegExp(`(${query})`, 'gi'));
      return parts.map((part, index) => 
        part.toLowerCase() === query.toLowerCase() 
          ? <mark key={index} style={{ backgroundColor: theme.palette.warning.light }}>{part}</mark> 
          : part
      );
    } catch (e) {
      return text;
    }
  };
  
  // 摘要卡片组件
  const SummaryCard = ({ summary }: { summary: Summary }) => (
    <Card 
      sx={{ 
        mb: 2, 
        border: selectedSummary?.id === summary.id 
          ? `2px solid ${theme.palette.primary.main}` 
          : `1px solid ${theme.palette.divider}`
      }}
    >
      <CardContent>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', mb: 1 }}>
          <Box>
            <Typography variant="subtitle1" component="div" gutterBottom sx={{ fontWeight: 'bold' }}>
              {summary.fname || `摘要 #${summary.id}`}
            </Typography>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
              <Typography variant="caption" color="text.secondary">
                创建时间: {formatDate(summary.created_at)}
              </Typography>
              {summary.uploader && (
                <>
                  <Divider orientation="vertical" flexItem sx={{ mx: 0.5, height: 12 }} />
                  <Typography variant="caption" color="primary.main">
                    上传者: {summary.uploader.username}
                  </Typography>
                </>
              )}
            </Box>
          </Box>
          <IconButton 
            size="small" 
            onClick={(e) => handleMoreClick(e, summary.id)}
            aria-label="更多操作"
          >
            <MoreVertIcon fontSize="small" />
          </IconButton>
        </Box>
        
        <Typography 
          variant="body2" 
          component="div" 
          sx={{ 
            mb: 2, 
            overflow: 'hidden',
            display: '-webkit-box',
            WebkitBoxOrient: 'vertical',
            WebkitLineClamp: 3,
            textOverflow: 'ellipsis'
          }}
        >
          {highlightText(summary.summary, searchParams.query)}
        </Typography>
        
        {summary.keywords && (
          <Box sx={{ mt: 1, display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
            {summary.keywords.split(',').map((keyword, index) => (
              <Chip 
                key={index} 
                label={keyword.trim()} 
                size="small" 
                color={keyword.trim().toLowerCase().includes(searchParams.query.toLowerCase()) ? "primary" : "default"}
                sx={{ mr: 0.5, mb: 0.5 }}
                onClick={() => {
                  setSearchValue(keyword.trim());
                  setSearchParams(prev => ({ 
                    ...prev, 
                    query: keyword.trim(), 
                    page: 1,
                    search_type: 'keywords'
                  }));
                }}
              />
            ))}
          </Box>
        )}
        
        {summary.coreference_text && (
          <Box sx={{ mt: 1, display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
            {summary.coreference_text.split(';').map((coreference, index) => (
              <Chip 
                key={index} 
                label={coreference.trim()} 
                size="small"
                color="secondary"
                sx={{ mr: 0.5, mb: 0.5 }}
              />
            ))}
          </Box>
        )}
        
        <Box sx={{ mt: 2, display: 'flex', justifyContent: 'flex-end' }}>
          <Button
            variant="outlined"
            size="small"
            startIcon={<VisibilityIcon />}
            onClick={() => handleViewDetail(summary)}
          >
            查看详情
          </Button>
        </Box>
      </CardContent>
    </Card>
  );
  
  // 打开编辑对话框
  const handleEditSummary = (summary: Summary) => {
    setSelectedSummary(summary);
    setEditedSummary(summary.summary);
    setEditDialogOpen(true);
    handleMoreClose();
  };
  
  // 保存编辑后的摘要
  const handleSaveSummary = async () => {
    try {
      if (!selectedSummary) return;
      
      setLoading(true);
      
      // 调用API保存修改后的摘要
      const response = await dataApi.updateSummary(selectedSummary.id, {
        summary: editedSummary
      });
      
      // 获取更新后的摘要数据
      const updatedSummary = response.data.summary;
      
      // 更新当前显示的摘要
      setSelectedSummary(updatedSummary);
      
      // 更新搜索结果中的摘要
      if (searchResults) {
        const updatedSummaries = searchResults.summaries.map(s => 
          s.id === updatedSummary.id ? updatedSummary : s
        );
        setSearchResults({
          ...searchResults,
          summaries: updatedSummaries
        });
      }
      
      setEditDialogOpen(false);
      
      // 显示成功消息
      setSuccessMessage('摘要更新成功');
      setSnackbarOpen(true);
      
    } catch (error: any) {
      console.error('保存摘要失败:', error);
      setError(error.response?.data?.error || '保存摘要失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };
  
  // 处理Snackbar关闭
  const handleSnackbarClose = (event?: React.SyntheticEvent | Event, reason?: string) => {
    if (reason === 'clickaway') {
      return;
    }
    setSnackbarOpen(false);
  };
  
  // 使用AI重新生成摘要
  const handleRegenerateSummary = async () => {
    try {
      if (!selectedSummary) return;
      
      setRegenerating(true);
      
      // 使用模型直接生成摘要，而不创建聊天记录
      const response = await dataApi.generateSummary({
        dialogue: selectedSummary.dialogue,
        model: selectedModel,
        summary_id: selectedSummary.id
      });
      
      // 获取生成的新摘要
      const newSummary = response.data.summary;
      
      // 更新编辑框中的内容
      setEditedSummary(newSummary);
      
    } catch (error: any) {
      console.error('重新生成摘要失败:', error);
      setError(error.response?.data?.error || '重新生成摘要失败，请稍后重试');
    } finally {
      setRegenerating(false);
    }
  };
  
  // 处理模型选择变更
  const handleModelChange = (event: SelectChangeEvent) => {
    setSelectedModel(event.target.value);
  };
  
  // 处理聊天记录筛选变更
  const handleChatOnlyChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setSearchParams(prev => ({
      ...prev,
      chat_only: event.target.checked,
      page: 1 // 重置页码
    }));
  };
  
  return (
    <Box sx={{ p: 3, maxWidth: 1200, margin: '0 auto' }}>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', mb: 3 }}>
        <Box sx={{ display: 'flex', alignItems: 'flex-start' }}>
          <IconButton 
            onClick={() => navigate('/chat')} 
            sx={{ mr: 2, mt: -0.5 }}
            aria-label="返回"
          >
            <ArrowBackIcon />
          </IconButton>
          <Box>
            <Typography variant="h5" gutterBottom fontWeight="bold">
              摘要查询
            </Typography>
            <Typography variant="body2" color="text.secondary">
              {currentUser?.role === 'admin' 
                ? '作为管理员，您可以查看所有用户上传的摘要内容' 
                : '您可以查看所有您上传的摘要内容'}
            </Typography>
          </Box>
        </Box>
      </Box>
      
      <Paper sx={{ p: 3, mb: 3 }}>
        <form onSubmit={handleSearchSubmit}>
          <Grid container spacing={2} alignItems="center">
            <Grid item xs={12} md={6}>
              <TextField
                value={searchValue}
                onChange={(e) => setSearchValue(e.target.value)}
                placeholder="搜索摘要、对话或关键词..."
                variant="outlined"
                fullWidth
                InputProps={{
                  startAdornment: (
                    <InputAdornment position="start">
                      <SearchIcon />
                    </InputAdornment>
                  ),
                  endAdornment: searchValue && (
                    <InputAdornment position="end">
                      <IconButton size="small" onClick={handleClearSearch}>
                        <ClearIcon fontSize="small" />
                      </IconButton>
                    </InputAdornment>
                  )
                }}
              />
            </Grid>
            <Grid item xs={12} md={3}>
              <FormControl fullWidth>
                <InputLabel id="search-type-label">搜索范围</InputLabel>
                <Select
                  labelId="search-type-label"
                  value={searchParams.search_type}
                  label="搜索范围"
                  onChange={handleSearchTypeChange}
                >
                  <MenuItem value="all">全部</MenuItem>
                  <MenuItem value="summary">仅摘要</MenuItem>
                  <MenuItem value="dialogue">仅对话</MenuItem>
                  <MenuItem value="keywords">仅关键词</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            <Grid item xs={12} md={3}>
              <Box sx={{ display: 'flex', gap: 1 }}>
                <Button
                  variant="contained"
                  color="primary"
                  type="submit"
                  fullWidth
                  startIcon={<SearchIcon />}
                  disabled={loading}
                >
                  {loading ? <CircularProgress size={24} /> : '搜索'}
                </Button>
                <Button
                  variant="outlined"
                  color="primary"
                  onClick={handleFilterClick}
                  sx={{ minWidth: 'auto', px: 1 }}
                >
                  <FilterIcon />
                </Button>
              </Box>
            </Grid>
          </Grid>
        </form>
      </Paper>
      
      {error && (
        <Alert severity="error" sx={{ mb: 3 }}>
          {error}
        </Alert>
      )}
      
      <Grid container spacing={3}>
        <Grid item xs={12}>
          {loading && !searchResults ? (
            // 加载中骨架屏
            Array(3).fill(0).map((_, i) => (
              <Card key={i} sx={{ mb: 2 }}>
                <CardContent>
                  <Skeleton variant="text" width="60%" height={30} />
                  <Skeleton variant="text" width="30%" height={20} sx={{ mb: 1 }} />
                  <Skeleton variant="text" width="100%" height={20} />
                  <Skeleton variant="text" width="100%" height={20} />
                  <Skeleton variant="text" width="90%" height={20} sx={{ mb: 1 }} />
                  <Box sx={{ display: 'flex', gap: 1, mt: 1 }}>
                    <Skeleton variant="rounded" width={60} height={25} />
                    <Skeleton variant="rounded" width={60} height={25} />
                    <Skeleton variant="rounded" width={60} height={25} />
                  </Box>
                </CardContent>
              </Card>
            ))
          ) : searchResults && searchResults.summaries.length > 0 ? (
            <Box>
              <Typography variant="subtitle1" gutterBottom>
                找到 {searchResults.total} 条结果
                {searchParams.query && (
                  <span> - 搜索词: "{searchParams.query}"</span>
                )}
              </Typography>
              
              {searchResults.summaries.map((summary) => (
                <SummaryCard key={summary.id} summary={summary} />
              ))}
              
              {searchResults.total > searchParams.per_page && (
                <Box sx={{ mt: 4, display: 'flex', justifyContent: 'center' }}>
                  <Pagination
                    count={Math.ceil(searchResults.total / searchParams.per_page)}
                    page={searchResults.page}
                    onChange={handlePageChange}
                    color="primary"
                  />
                </Box>
              )}
            </Box>
          ) : searchResults && searchResults.summaries.length === 0 ? (
            <Box sx={{ textAlign: 'center', py: 8 }}>
              <SummaryIcon sx={{ fontSize: 60, color: 'text.disabled', mb: 2 }} />
              <Typography color="textSecondary">
                {searchParams.query 
                  ? `没有找到与 "${searchParams.query}" 相关的摘要` 
                  : '暂无摘要数据，请先上传数据'}
              </Typography>
              {searchParams.query && (
                <Button
                  variant="text"
                  color="primary"
                  onClick={handleClearSearch}
                  sx={{ mt: 2 }}
                >
                  清除搜索条件
                </Button>
              )}
            </Box>
          ) : null}
        </Grid>
      </Grid>
      
      {/* 筛选菜单 */}
      <Menu
        id="filter-menu"
        anchorEl={filterAnchorEl}
        open={filterOpen}
        onClose={handleFilterClose}
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'right',
        }}
        transformOrigin={{
          vertical: 'top',
          horizontal: 'right',
        }}
      >
        <MenuItem>
          <FormControl component="fieldset">
            <Typography variant="subtitle2" gutterBottom>
              搜索范围
            </Typography>
            <Select
              value={searchParams.search_type}
              onChange={handleSearchTypeChange}
              size="small"
              sx={{ minWidth: 150 }}
            >
              <MenuItem value="all">所有字段</MenuItem>
              <MenuItem value="summary">仅摘要</MenuItem>
              <MenuItem value="dialogue">仅对话</MenuItem>
              <MenuItem value="keywords">仅关键词</MenuItem>
            </Select>
          </FormControl>
        </MenuItem>
        <Divider sx={{ my: 1 }} />
        <MenuItem>
          <FormControlLabel
            control={
              <Switch
                checked={searchParams.chat_only}
                onChange={handleChatOnlyChange}
                name="chatOnly"
              />
            }
            label="仅显示聊天记录"
          />
        </MenuItem>
        <Divider sx={{ my: 1 }} />
        <ListSubheader>每页显示数量</ListSubheader>
        {[10, 20, 50].map(size => (
          <MenuItem 
            key={size}
            selected={searchParams.per_page === size}
            onClick={() => {
              setSearchParams(prev => ({ ...prev, per_page: size, page: 1 }));
              handleFilterClose();
            }}
          >
            {size} 条
          </MenuItem>
        ))}
      </Menu>
      
      {/* 更多操作菜单 */}
      <Menu
        anchorEl={moreAnchorEl}
        open={Boolean(moreAnchorEl)}
        onClose={handleMoreClose}
      >
        <MenuItem onClick={() => {
          const summary = searchResults?.summaries.find(s => s.id === activeSummaryId);
          if (summary) {
            handleViewDetail(summary);
          }
        }}>
          <ListItemIcon>
            <VisibilityIcon fontSize="small" />
          </ListItemIcon>
          <ListItemText>查看详情</ListItemText>
        </MenuItem>
        <MenuItem onClick={() => {
          const summary = searchResults?.summaries.find(s => s.id === activeSummaryId);
          if (summary) {
            handleEditSummary(summary);
          }
        }}>
          <ListItemIcon>
            <EditIcon fontSize="small" />
          </ListItemIcon>
          <ListItemText>编辑摘要</ListItemText>
        </MenuItem>
        <MenuItem onClick={() => {
          const summary = searchResults?.summaries.find(s => s.id === activeSummaryId);
          if (summary) {
            handleCopySummary(summary.summary);
          }
        }}>
          <ListItemIcon>
            <CopyIcon fontSize="small" />
          </ListItemIcon>
          <ListItemText>复制摘要</ListItemText>
        </MenuItem>
      </Menu>
      
      {/* 详情查看对话框 */}
      <Dialog
        open={detailDialogOpen}
        onClose={() => setDetailDialogOpen(false)}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>
          查看详情
          {selectedSummary && (
            <Box sx={{ mt: 0.5 }}>
              <Typography variant="subtitle2" color="text.secondary">
                {selectedSummary.fname || `摘要 #${selectedSummary.id}`}
              </Typography>
              {selectedSummary.uploader && (
                <Typography variant="caption" color="primary.main" sx={{ display: 'block', mt: 0.5 }}>
                  上传者: {selectedSummary.uploader.username} (ID: {selectedSummary.uploader.id})
                </Typography>
              )}
            </Box>
          )}
        </DialogTitle>
        <DialogContent dividers>
          {selectedSummary && (
            <>
              <Tabs
                value={detailView}
                onChange={handleDetailViewChange}
                sx={{ mb: 2 }}
              >
                <Tab 
                  icon={<SummaryIcon fontSize="small" />} 
                  iconPosition="start" 
                  label="摘要" 
                  value="summary" 
                />
                <Tab 
                  icon={<DialogueIcon fontSize="small" />} 
                  iconPosition="start" 
                  label="对话" 
                  value="dialogue" 
                />
              </Tabs>
              
              <Divider sx={{ mb: 2 }} />
              
              {detailView === 'summary' ? (
                <Box>
                  <Typography variant="subtitle2" gutterBottom>摘要内容:</Typography>
                  <Paper 
                    variant="outlined" 
                    sx={{ 
                      p: 2, 
                      mb: 2, 
                      backgroundColor: theme.palette.background.default 
                    }}
                  >
                    <Typography variant="body1">
                      {highlightText(selectedSummary.summary, searchParams.query)}
                    </Typography>
                  </Paper>
                  
                  <Box sx={{ display: 'flex', justifyContent: 'flex-end' }}>
                    <Button
                      variant="outlined"
                      size="small"
                      startIcon={<CopyIcon />}
                      onClick={() => handleCopySummary(selectedSummary.summary)}
                      sx={{ mr: 1 }}
                    >
                      复制摘要
                    </Button>
                    <Button
                      variant="outlined"
                      size="small"
                      startIcon={<EditIcon />}
                      onClick={() => {
                        setDetailDialogOpen(false);
                        setEditDialogOpen(true);
                        setEditedSummary(selectedSummary.summary);
                      }}
                    >
                      编辑摘要
                    </Button>
                  </Box>
                </Box>
              ) : (
                <Box>
                  <Typography variant="subtitle2" gutterBottom>对话内容:</Typography>
                  <Paper 
                    variant="outlined" 
                    sx={{ 
                      p: 2, 
                      mb: 2, 
                      maxHeight: 400, 
                      overflow: 'auto',
                      backgroundColor: theme.palette.background.default 
                    }}
                  >
                    <Typography 
                      variant="body2" 
                      component="pre" 
                      sx={{ whiteSpace: 'pre-wrap', fontFamily: 'inherit' }}
                    >
                      {highlightText(selectedSummary.dialogue, searchParams.query)}
                    </Typography>
                  </Paper>
                  
                  <Box sx={{ display: 'flex', justifyContent: 'flex-end' }}>
                    <Button
                      variant="outlined"
                      size="small"
                      startIcon={<CopyIcon />}
                      onClick={() => handleCopySummary(selectedSummary.dialogue)}
                    >
                      复制对话
                    </Button>
                  </Box>
                </Box>
              )}
              
              {selectedSummary.keywords && (
                <Box sx={{ mt: 3 }}>
                  <Typography variant="subtitle2" gutterBottom>关键词:</Typography>
                  <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
                    {selectedSummary.keywords.split(',').map((keyword, index) => (
                      <Chip 
                        key={index} 
                        label={keyword.trim()} 
                        size="small" 
                        color={keyword.trim().toLowerCase().includes(searchParams.query.toLowerCase()) ? "primary" : "default"}
                        sx={{ mr: 0.5, mb: 0.5 }}
                        onClick={() => {
                          setSearchValue(keyword.trim());
                          setSearchParams(prev => ({ 
                            ...prev, 
                            query: keyword.trim(), 
                            page: 1,
                            search_type: 'keywords'
                          }));
                          setDetailDialogOpen(false);
                        }}
                      />
                    ))}
                  </Box>
                </Box>
              )}
              
              {selectedSummary.coreference_text && (
                <Box sx={{ mt: 3 }}>
                  <Typography variant="subtitle2" gutterBottom>参考文本:</Typography>
                  <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
                    {selectedSummary.coreference_text.split(';').map((coreference, index) => (
                      <Chip 
                        key={index} 
                        label={coreference.trim()} 
                        size="small" 
                        color="secondary"
                        sx={{ mr: 0.5, mb: 0.5 }}
                      />
                    ))}
                  </Box>
                </Box>
              )}
              
              <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: 2 }}>
                创建时间: {formatDate(selectedSummary.created_at)}
              </Typography>
            </>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDetailDialogOpen(false)}>关闭</Button>
        </DialogActions>
      </Dialog>
      
      {/* 编辑摘要对话框 */}
      <Dialog
        open={editDialogOpen}
        onClose={() => setEditDialogOpen(false)}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>
          编辑摘要
          {selectedSummary && (
            <Box sx={{ mt: 0.5 }}>
              <Typography variant="subtitle2" color="text.secondary">
                {selectedSummary.fname || `摘要 #${selectedSummary.id}`}
              </Typography>
              {selectedSummary.uploader && (
                <Typography variant="caption" color="primary.main" sx={{ display: 'block', mt: 0.5 }}>
                  上传者: {selectedSummary.uploader.username} (ID: {selectedSummary.uploader.id})
                </Typography>
              )}
            </Box>
          )}
        </DialogTitle>
        <DialogContent dividers>
          {selectedSummary && (
            <>
              <Typography variant="subtitle2" gutterBottom>原始对话:</Typography>
              <Paper 
                variant="outlined" 
                sx={{ 
                  p: 2, 
                  mb: 3, 
                  maxHeight: 200, 
                  overflow: 'auto',
                  backgroundColor: theme.palette.background.default
                }}
              >
                <Typography variant="body2" component="pre" sx={{ whiteSpace: 'pre-wrap', fontFamily: 'inherit' }}>
                  {selectedSummary.dialogue}
                </Typography>
              </Paper>
              
              <Box sx={{ mb: 2, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <Typography variant="subtitle2">摘要内容:</Typography>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <FormControl size="small" sx={{ minWidth: 120 }}>
                    <InputLabel id="model-select-label">选择模型</InputLabel>
                    <Select
                      labelId="model-select-label"
                      value={selectedModel}
                      label="选择模型"
                      onChange={handleModelChange}
                      size="small"
                    >
                      <MenuItem value="model_1">模型一</MenuItem>
                      <MenuItem value="model_2">模型二</MenuItem>
                      <MenuItem value="model_3">模型三</MenuItem>
                    </Select>
                    <FormHelperText>选择AI模型</FormHelperText>
                  </FormControl>
                  <Button
                    variant="outlined"
                    startIcon={<RefreshIcon />}
                    size="small"
                    onClick={handleRegenerateSummary}
                    disabled={regenerating}
                  >
                    {regenerating ? <CircularProgress size={24} /> : '重新生成'}
                  </Button>
                </Box>
              </Box>
              
              <TextareaAutosize
                value={editedSummary}
                onChange={(e) => setEditedSummary(e.target.value)}
                style={{
                  width: '100%',
                  minHeight: 200,
                  padding: 16,
                  fontFamily: 'inherit',
                  fontSize: '1rem',
                  borderRadius: 4,
                  border: `1px solid ${theme.palette.divider}`,
                  resize: 'vertical',
                }}
                placeholder="编辑摘要内容..."
              />
            </>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setEditDialogOpen(false)}>取消</Button>
          <Button 
            onClick={handleSaveSummary} 
            variant="contained" 
            disabled={loading}
          >
            {loading ? <CircularProgress size={24} /> : '保存修改'}
          </Button>
        </DialogActions>
      </Dialog>
      
      {/* 添加Snackbar组件 */}
      <Snackbar
        open={snackbarOpen}
        autoHideDuration={5000}
        onClose={handleSnackbarClose}
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
      >
        <Alert 
          onClose={handleSnackbarClose} 
          severity="success" 
          variant="filled" 
          sx={{ width: '100%' }}
        >
          {successMessage}
        </Alert>
      </Snackbar>
    </Box>
  );
};

export default SummarySearch; 